package com.rcloud.stock.adapter;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.rcloud.stock.R;
import com.rcloud.stock.bean.Stock;

public class SearchAnswerAdapter extends ListAdapter<Stock, SearchAnswerAdapter.ViewHolder> {
    public SearchAnswerAdapter() {
        super(new DiffUtil.ItemCallback<Stock>() {
            @Override
            public boolean areItemsTheSame(@NonNull Stock oldItem, @NonNull Stock newItem) {
                return oldItem.getCode().equals(newItem.getCode());
            }

            @Override
            public boolean areContentsTheSame(@NonNull Stock oldItem, @NonNull Stock newItem) {
                return oldItem.getName().equals(newItem.getName());
            }
        });
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_search_answer,parent,false);
        ViewHolder holder = new ViewHolder(view);
        holder.itemView.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("stock",(Stock) v.getTag(R.integer.history_tag));
            NavController controller = Navigation.findNavController(v);
            controller.navigate(R.id.action_searchFragment_to_detailFragment,bundle);
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.stockName.setText(getItem(position).getCode());
        holder.stockCode.setText(getItem(position).getName());
        holder.itemView.setTag(R.integer.history_tag,getItem(position));
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        private final TextView stockCode;
        private final TextView stockName;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            stockCode = itemView.findViewById(R.id.search_stock_code);
            stockName = itemView.findViewById(R.id.search_stock_name);
        }
    }
}